package com.ed.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ed.domain.ChatConversation;
import com.ed.domain.ChatMessage;
import com.ed.domain.User;
import com.ed.dto.PageAIRecordsByConditionDTO;
import com.ed.exception.BaseException;
import com.ed.mapper.IChatConversationMapper;
import com.ed.result.PageResult;
import com.ed.result.Result;
import com.ed.service.ChatConversationService;
import com.ed.service.ChatMessageService;
import com.ed.service.UserService;
import com.ed.vo.AIRecordsDetailsVO;
import com.ed.vo.AIUseInfoVO;
import com.ed.vo.PageAIRecordsByConditionVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理员数据总览
 */
@RestController
@Slf4j
@CrossOrigin
@RequiredArgsConstructor
@RequestMapping("/AIUsingAnalysis")
public class AIUsingAnalysisController {
	
	private final ChatConversationService chatConversationService;
	private final ChatMessageService chatMessageService;
	private final IChatConversationMapper chatConversationMapper;
	private final UserService userService;
	
	/**
	 * 管理员获取 ai 使用信息
	 *
	 * @return ai使用总次数、活跃用户数
	 */
	@GetMapping("/getAIInfo")
	public Result<AIUseInfoVO> getAIInfo() {
		Long count = chatMessageService.lambdaQuery().eq(ChatMessage::getRole, "assistant").count();
		if (count == null || count < 0) {
			throw new BaseException("ai 使用次数统计异常");
		}
		long userCount = chatConversationMapper.countUserIdDistinct();
		AIUseInfoVO aiUseInfoVO = new AIUseInfoVO();
		aiUseInfoVO.setUseCount(count);
		aiUseInfoVO.setUserCount(userCount);
		return Result.success(aiUseInfoVO);
	}
	
	/**
	 * 根据用户或问题搜索记录
	 *
	 * @param pageAIRecordsByConditionDTO 姓名 问题
	 * @return id、用户姓名、问题的前10个字符、ai回答的前10个字符
	 */
	@GetMapping("/pageAIRecordsByCondition")
	public Result<PageResult> pageAIRecordsByCondition(
		//1.获取参数
		PageAIRecordsByConditionDTO pageAIRecordsByConditionDTO) {
		String name = pageAIRecordsByConditionDTO.getName();
		String question = pageAIRecordsByConditionDTO.getQuestion();
		Integer pageNo = pageAIRecordsByConditionDTO.getPageNo();
		Integer pageSize = pageAIRecordsByConditionDTO.getPageSize();
		if (pageNo == null || pageNo < 0) {
			pageNo = 0;
		}
		if (pageSize == null || pageSize < 0) {
			pageSize = 10;
		}
		//初始化 查询问题 chatMessageWrapper
		LambdaQueryWrapper<ChatMessage> chatMessageWrapper = new LambdaQueryWrapper<>();
		chatMessageWrapper.eq(ChatMessage::getRole, "user");
		//2.根据姓名搜索记录
		if (StrUtil.isNotBlank(name)) {
			List<Integer> userIds = userService.lambdaQuery()
				.like(User::getName, name)
				.select(User::getId)
				.list().stream()
				.map(User::getId)
				.collect(Collectors.toList());
			if (CollUtil.isEmpty(userIds)) {
				//搜索姓名不存在，直接返回
				PageResult pageResult = new PageResult();
				pageResult.setTotal(0);
				pageResult.setRecords(new ArrayList<>());
				return Result.success(pageResult);
			}
			List<String> conversationIds = chatConversationService.lambdaQuery()
				.in(ChatConversation::getUserId, userIds)
				.select(ChatConversation::getConversationId)
				.list().stream()
				.map(ChatConversation::getConversationId)
				.collect(Collectors.toList());
			chatMessageWrapper.in(ChatMessage::getConversationId, conversationIds);
		}
		//3.根据问题搜索记录
		if (StrUtil.isNotBlank(question)) {
			chatMessageWrapper.like(ChatMessage::getContent, question);
		}
		//4.根据姓名和问题分页查询
		Page<ChatMessage> page = chatMessageService
			.page(new Page<>(pageNo, pageSize), chatMessageWrapper);
		List<ChatMessage> chatMessages = page.getRecords();
		if (chatMessages == null || CollUtil.isEmpty(chatMessages)) {
			PageResult pageResult = new PageResult();
			pageResult.setTotal(page.getTotal());
			pageResult.setRecords(new ArrayList<>());
			return Result.success(pageResult);
		}
		//5.查询关联回答
		// a.获取关联回答id
		List<Integer> replyChatMessagesIds = chatMessages.stream()
			.map(ChatMessage::getReplyId)
			.collect(Collectors.toList());
		// b.查询关联回答
		List<ChatMessage> replyChatMessages = chatMessageService.lambdaQuery()
			.in(ChatMessage::getId, replyChatMessagesIds)
			.list();
		// c.获取关联回答所属会话ids，用于获取用户信息
		List<String> replyConversationIds = replyChatMessages.stream()
			.map(ChatMessage::getConversationId)
			.collect(Collectors.toList());
		// d.messageId 与 关联回答 的映射 map，用于关联回答
		Map<Integer, List<ChatMessage>> chatMessageMap = replyChatMessages.stream()
			.collect(Collectors.groupingBy(ChatMessage::getId));
		//6.关联用户姓名
		// a.根据会话ids，查询会话实体
		List<ChatConversation> chatConversations = chatConversationService.lambdaQuery()
			.in(ChatConversation::getConversationId, replyConversationIds)
			.select(ChatConversation::getUserId, ChatConversation::getConversationId)
			.list();
		// b.用户ids
		List<Integer> userIds = chatConversations.stream()
			.map(ChatConversation::getUserId)
			.collect(Collectors.toList());
		// c.会话id 与 用户id 的映射map
		Map<String, List<ChatConversation>> chatConversationMap = chatConversations
			.stream()
			.collect(Collectors.groupingBy(ChatConversation::getConversationId));
		// d.用户id 与 用户信息 的映射map
		Map<Integer, List<User>> userMap = userService.lambdaQuery()
			.in(User::getId, userIds)
			.select(User::getId, User::getName)
			.list().stream()
			.collect(Collectors.groupingBy(User::getId));
		//7.构建响应结果
		List<PageAIRecordsByConditionVO> result = chatMessages.stream()
			.map(message -> {
				PageAIRecordsByConditionVO vo = new PageAIRecordsByConditionVO();
				String conversationId = message.getConversationId();
				vo.setId(message.getId());
				vo.setConId(conversationId);
				vo.setQuestion(StrUtil.subPre(message.getContent(), 10));
				//关联用户名
				List<ChatConversation> conversations = chatConversationMap.get(conversationId);
				if (CollUtil.isNotEmpty(conversations)) {
					Integer userId = conversations.get(0).getUserId();
					List<User> users = userMap.get(userId);
					if (CollUtil.isNotEmpty(users)) {
						vo.setName(users.get(0).getName());
					}
				}
				//关联回答
				List<ChatMessage> messList = chatMessageMap.get(message.getReplyId());
				if (CollUtil.isNotEmpty(messList)) {
					String answer = messList.get(0).getContent();
					vo.setAnswer(StrUtil.subPre(answer, 10));
				}
				return vo;
			}).collect(Collectors.toList());
		//8.构建分页响应对象，返回
		PageResult pageResult = new PageResult();
		pageResult.setTotal(page.getTotal());
		pageResult.setRecords(result);
		return Result.success(pageResult);
	}
	
	
	/**
	 * 查询详情
	 *
	 * @return
	 */
	@GetMapping("/AIRecordsDetails")
	public Result<AIRecordsDetailsVO> AIRecordsDetails(Integer messageId) {
		ChatMessage questionChatMessage = chatMessageService.lambdaQuery()
			.eq(ChatMessage::getId, messageId)
			.select(ChatMessage::getContent, ChatMessage::getReplyId)
			.one();
		ChatMessage answerChatMessage = chatMessageService.lambdaQuery()
			.eq(ChatMessage::getId, questionChatMessage.getReplyId())
			.select(ChatMessage::getContent)
			.one();
		AIRecordsDetailsVO vo = new AIRecordsDetailsVO();
		vo.setQuestion(questionChatMessage.getContent());
		vo.setAnswer(answerChatMessage.getContent());
		return Result.success(vo);
	}
}
